﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace exp2
{
    public partial class Form1 : Form
    {
        string message;
        SerialPort sPort = new SerialPort();

        public Form1()
        {
            InitializeComponent();
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

            cbBaudRate.SelectedIndex = 0;//设置初始状态
            cbDataBits.SelectedIndex = 0;
            cbParity.SelectedIndex = 0;
            cbStopBits.SelectedIndex = 0;

            string[] strCom = SerialPort.GetPortNames();//GetPortNames():获取当前计算机的串行端口名的数组

            if (strCom == null)
            {
                MessageBox.Show("没有找到串口", "Error");
                return;
            }

            foreach (string comname in System.IO.Ports.SerialPort.GetPortNames())//获取串口号
            {
                cbCom.Items.Add(comname);//添加到combobox
            }

            cbCom.SelectedIndex = 0;
            sPort.BaudRate = 9600;  //在该类的第一句创建的串口对象 SerialPort sPort = new SerialPort();

            Control.CheckForIllegalCrossThreadCalls = false;  //安全的访问窗体控件
            sPort.DataReceived += sPort_DataReceived;//添加对接收数据的事件的监听

            sPort.DtrEnable = true;// 该值在串行通信过程中启用数据终端就绪(DTR) 信号。
            sPort.RtsEnable = true;//该值指示在串行通信中启用请求发送 (RTS) 信号

            sPort.ReadTimeout = 1000;  // 数据读取超时为1s

            sPort.Close();
        }
        private void sPort_DataReceived(object sender, SerialDataReceivedEventArgs e)  //Form1_Load里创建自动生成
        {

            //接受信息

            if (sPort.IsOpen)
            {
                try
                {
                    Byte[] receivedData = new Byte[sPort.BytesToRead]; //创建接收字节数组
                    sPort.Read(receivedData, 0, receivedData.Length);  //读取数据
                    AddContent(new UTF8Encoding().GetString(receivedData));//使用UTF8，可以传输中文
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                    dataSend1.Text = "";
                }

            }
            else
                MessageBox.Show("请打开串口", "Error");

        }

        private void AddContent(string data)
        {
            this.BeginInvoke(new MethodInvoker(delegate//使用invoke
            {

                System.DateTime curTime = new System.DateTime();//获取接收时间
                curTime = System.DateTime.Now;
                dataReceived.AppendText("[RECV " + curTime.ToString() + "] ");//显示接收时间
                dataReceived.AppendText(data + "\r\n");

            }));
        }


        private void dataSent1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btOpen_Click(object sender, EventArgs e)
        {

            if (!sPort.IsOpen)
            {
                try
                {

                    sPort.PortName = cbCom.SelectedItem.ToString();//获取串口名

                    sPort.BaudRate = Convert.ToInt32(cbBaudRate.Text);//获取波特率，将文本转化为整数
                    sPort.DataBits = Convert.ToInt32(cbDataBits.Text);//获取校验位

                    //设置校验位
                    if (cbStopBits.Text.Equals("1"))
                        sPort.StopBits = System.IO.Ports.StopBits.One;
                    else if (cbStopBits.Text.Equals("1.5"))
                        sPort.StopBits = System.IO.Ports.StopBits.OnePointFive;
                    else if (cbStopBits.Text.Equals("2"))
                        sPort.StopBits = System.IO.Ports.StopBits.Two;

                    //设置停止位
                    switch (cbParity.Text)
                    {
                        case "None":
                            sPort.Parity = Parity.None;
                            break;
                        case "Odd":
                            sPort.Parity = Parity.Odd;
                            break;
                        case "Even":
                            sPort.Parity = Parity.Even;
                            break;
                        case "Mark":
                            sPort.Parity = Parity.Mark;
                            break;
                        case "Space":
                            sPort.Parity = Parity.Space;
                            break;
                        default:
                            MessageBox.Show("Error：参数异常", "Error");
                            break;
                    }

                    if (sPort.IsOpen == true)
                    {
                        sPort.Close();
                    }

                    cbCom.Enabled = false;//控件设置为不可用，即串口设置不可改变
                    cbDataBits.Enabled = false;
                    cbStopBits.Enabled = false;
                    cbParity.Enabled = false;
                    cbBaudRate.Enabled = false;
                    sPort.Open();//打开串口
                    btOpen.Text = "关闭串口";//改变按钮文字
                    btOpen.BackColor = Color.DarkSeaGreen;//改变按钮颜色

                }

                catch (System.Exception ex)
                {
                    MessageBox.Show("Error:" + ex.Message, "Error");//向串口写入数据
                    return;
                }

            }

            else
            {
                cbCom.Enabled = true;//控件可用，即串口设置为可变
                cbBaudRate.Enabled = true;
                cbDataBits.Enabled = true;
                cbStopBits.Enabled = true;
                cbParity.Enabled = true;
                sPort.Close();//关闭串口
                btOpen.Text = "打开串口";
                btOpen.BackColor = Color.LightSteelBlue;
            }

        }

        private void btSend_Click(object sender, EventArgs e)
        {

            byte[] sendData = null;
            if (!sPort.IsOpen)
            {
                MessageBox.Show("请先打开串口", "Error");
                return;
            }
            string strSend = dataSent2.Text;
            if (sPort.IsOpen)
            {
                System.DateTime curTime = new System.DateTime();
                curTime = System.DateTime.Now;//获取当前时间
                message = dataSend1.Text;
                dataSent2.Text += "[SENT " + curTime.ToString() + "] " + message;//显示发送时间
                message = "[SENT " + curTime.ToString() + "] " + dataSend1.Text;
                dataSent2.AppendText("\r\n");
            }

            try
            {
                sendData = Encoding.UTF8.GetBytes(message.Trim());
                sPort.Write(sendData, 0, sendData.Length);//向串口写入数据
            }
            catch (Exception ex)//异常
            {
                MessageBox.Show("Error:" + ex.Message, "Error");
            }
        }

        private void btclose1_Click(object sender, EventArgs e)
        {
            dataSend1.Text = "";//清空
        }

        private void btclose2_Click(object sender, EventArgs e)
        {
            dataSent2.Text = "";
        }

        private void btclose3_Click(object sender, EventArgs e)
        {
            dataReceived.Text = "";
        }
    }
}
